package cn.zhibang.yygh.user.service.impl;

import cn.zhibang.yygh.common.exception.YyghException;
import cn.zhibang.yygh.common.handler.utils.HttpUtils;
import cn.zhibang.yygh.common.result.ResultCodeEnum;
import cn.zhibang.yygh.common.util.JwtHelper;
import cn.zhibang.yygh.enums.AuthStatusEnum;
import cn.zhibang.yygh.model.user.IdCardOne;
import cn.zhibang.yygh.model.user.Patient;
import cn.zhibang.yygh.model.user.UserInfo;
import cn.zhibang.yygh.user.mapper.UserInfoMapper;
import cn.zhibang.yygh.user.service.PatientService;
import cn.zhibang.yygh.user.service.UserInfoService;
import cn.zhibang.yygh.vo.user.LoginVo;
import cn.zhibang.yygh.vo.user.UserAuthVo;
import cn.zhibang.yygh.vo.user.UserInfoQueryVo;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService{
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Resource
    private PatientService patientService;
    @Override
    public Map<String, Object> login(LoginVo loginVo){
        String code = loginVo.getCode();
        String phone = loginVo.getPhone();
        System.err.println(code+"+"+phone);
        if(StringUtils.isEmpty(phone)||StringUtils.isEmpty(code)){
            throw new YyghException(ResultCodeEnum.PARAM_ERROR);
        }
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone",phone);
        UserInfo userInfo = baseMapper.selectOne(queryWrapper);
        if(null==userInfo){
            userInfo=new UserInfo();
            userInfo.setName("");
            userInfo.setPhone(phone);
            userInfo.setStatus(1);
            baseMapper.insert(userInfo);
        }
        if(userInfo.getStatus() == 0) {
            throw new YyghException(ResultCodeEnum.LOGIN_DISABLED_ERROR);
        }
        //校验校验验证码
//根据手机号码从redis中获得刚发送的验证码
        String mobleCode = redisTemplate.opsForValue().get(phone);
//比较验证码是否是相同的
        if(!code.equals(mobleCode)) {
            throw new YyghException(ResultCodeEnum.CODE_ERROR);
        }
        Map<String,Object> map = new HashMap<>();
        String name = userInfo.getName();
        if(StringUtils.isEmpty(name)){
            name=userInfo.getNickName();
        }
        if(StringUtils.isEmpty(name)){
            name=userInfo.getPhone();
        }
        map.put("name",name);
        String token = JwtHelper.createToken(userInfo.getId(), name);
        map.put("token", token);
        return map;
    }
    @Override
    public void userAuth(Long userId, UserAuthVo userAuthVo) {
        //根据用户id查询用户信息
        UserInfo userInfo = baseMapper.selectById(userId);
        //1.设置认证信息
        //认证人姓名
        userInfo.setName(userAuthVo.getName());
        //其他认证信息
        userInfo.setCertificatesType(userAuthVo.getCertificatesType());
        userInfo.setCertificatesNo(userAuthVo.getCertificatesNo());
        userInfo.setCertificatesUrl(userAuthVo.getCertificatesUrl());
        userInfo.setAuthStatus(AuthStatusEnum.AUTH_RUN.getStatus()); //状态
        //进行信息更新
        baseMapper.updateById(userInfo);
    }

    @Override
    public boolean IdCardTest(String Url) {
        //#######################
        ByteArrayOutputStream data = new ByteArrayOutputStream();
        try {
            URL url=new URL(Url);
            byte[] by = new byte[1024];
            HttpURLConnection coon= (HttpURLConnection) url.openConnection();
            coon.setRequestMethod("GET");
            coon.setConnectTimeout(5000);
            InputStream is = coon.getInputStream();
            int len =-1;
            while ((len=is.read(by))!=-1){
                data.write(by,0,len);
            }
            is.close();
        }catch (Exception e){
            e.printStackTrace();
        }
        Base64 base64 = new Base64();
        String base=base64.encodeToString(data.toByteArray());
        IdCardOne one = new IdCardOne();
        //###############################
        String host = "http://idccard.market.alicloudapi.com";
        String path = "/idcard";
        String method = "POST";
        String appcode = "06ffaea8ac7447cab8ee9b4d45f2f313";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/json; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        String bodys = "{\"media_id\":\""+base+"\"}";
        try {
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            String s = EntityUtils.toString(response.getEntity());
            System.out.println(s);
            System.out.println(response.getStatusLine().getStatusCode());
            if(response.getStatusLine().getStatusCode()!=200){
                return false;
            }
            one= JSON.parseObject(s, IdCardOne.class);
            System.out.println(one);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //#################################
        String host2 = "https://dfidveri.market.alicloudapi.com";
        String path2 = "/verify_id_name";
        String method2 = "POST";
        Map<String, String> headers2 = new HashMap<>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers2.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> querys2 = new HashMap<String, String>();
        Map<String, String> bodys2 = new HashMap<String, String>();
        bodys2.put("id_number", one.getData().getId_no());
        bodys2.put("name", one.getData().getName());
        int StatusCode=0;
        try {
            HttpResponse response = HttpUtils.doPost(host2, path2, method2, headers2, querys2, bodys2);
            System.err.println(response.getStatusLine().getStatusCode());
            StatusCode=response.getStatusLine().getStatusCode();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (StatusCode==200){
            return true;
        }else{
            return false;
        }

    }

    @Override
    public IPage<UserInfo> selectPage(Page<UserInfo> pageParam, UserInfoQueryVo userInfoQueryVo) {
        //UserInfoQueryVo获取条件值
        String name = userInfoQueryVo.getKeyword(); //用户名称
        Integer status = userInfoQueryVo.getStatus();//用户状态
        Integer authStatus = userInfoQueryVo.getAuthStatus(); //认证状态
        String createTimeBegin = userInfoQueryVo.getCreateTimeBegin(); //开始时间
        String createTimeEnd = userInfoQueryVo.getCreateTimeEnd(); //结束时间
        //对条件值进行非空判断
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(name)) {
            wrapper.like("name",name);
        }
        if(null!=status) {
            wrapper.eq("status",status);
        }
        if(null!=authStatus) {
            wrapper.eq("auth_status",authStatus);
        }
        if(!StringUtils.isEmpty(createTimeBegin)) {
            wrapper.ge("create_time",createTimeBegin);
        }
        if(!StringUtils.isEmpty(createTimeEnd)) {
            wrapper.le("create_time",createTimeEnd);
        }
        //调用mapper的方法
        IPage<UserInfo> pages = baseMapper.selectPage(pageParam,wrapper);
        System.out.println(pages.getTotal());
        //编号变成对应值封装
        pages.getRecords().stream().forEach(item -> {
            this.packageUserInfo(item);
        });
        return pages;
    }

    //编号变成对应值封装
    private UserInfo packageUserInfo(UserInfo userInfo) {
        //处理认证状态编码
        userInfo.getParam().put("authStatusString",AuthStatusEnum.getStatusNameByStatus(userInfo.getAuthStatus()));
        //处理用户状态 0  1
        String statusString = userInfo.getStatus().intValue()==0 ?"锁定" : "正常";
        userInfo.getParam().put("statusString",statusString);
        return userInfo;
    }
    @Override
    public void lock(Long userId, Integer status) {
        if(status.intValue() == 0 || status.intValue() == 1) {
            UserInfo userInfo = this.getById(userId);
            userInfo.setStatus(status);
            this.updateById(userInfo);
        }
    }
    //用户详情
    @Override
    public Map<String, Object> show(Long userId) {
        Map<String,Object> map = new HashMap<>();
        //根据userid查询用户信息
        UserInfo userInfo = this.packageUserInfo(baseMapper.selectById(userId));
        map.put("userInfo",userInfo);
        //根据userid查询就诊人信息
        List<Patient> patientList = patientService.findAllUserId(userId);
        map.put("patientList",patientList);
        return map;
    }
    @Override
    public void approval(Long userId, Integer authStatus) {
        if(authStatus.intValue()==2 || authStatus.intValue()==-1) {
            UserInfo userInfo = baseMapper.selectById(userId);
            userInfo.setAuthStatus(authStatus);
            baseMapper.updateById(userInfo);
        }
    }
}
